package com.fiveGroup.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fiveGroup.mapper.AddressMapper;
import com.fiveGroup.pojo.Address;
import com.fiveGroup.service.AddressService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 86188
 * @description 针对表【address(用户收货地址表)】的数据库操作Service实现
 * @createDate 2025-09-26 15:01:12
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address>
        implements AddressService {

    @Override
    public List<Address> getUserAddresses(Long userId) {
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public boolean updateAddress(Address address) {
        if (address.getIsDefault() == 1) { //设置当前地址为默认地址

            QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", address.getUserId());
            queryWrapper.eq("is_default", 1);
            Address address1 = new Address();
            address1.setUserId(address.getUserId());
            address1.setIsDefault(0);
            if (baseMapper.update(address1, queryWrapper) > 0) {
                return baseMapper.updateById(address) > 0;
            }
            return false;
        }
        return baseMapper.updateById(address) > 0;


    }

    @Override
    public boolean deleteAddress(Long id, Long userId) {
        // 验证地址属于当前用户
        Address address = baseMapper.selectById(id);
        if (address == null || !address.getUserId().equals(userId)) {
            return false;
        }

        return baseMapper.deleteById(id) > 0;
    }
}




